import os

def seek_start():
    """
    相对于开头进行偏移
    :return:
    """
    file = open('file1', mode='r+', encoding='utf8')
    # file.seek(8, os.SEEK_SET) # 相对于开头向前偏移6个字符，注意汉字偏移，一个汉字占三个字符
    text = file.read()
    print(text)
    file.close()


def seek_end():
    """
    相对于文件尾部偏移
    :return:
    """
    file = open('file1', mode='r+', encoding='utf8')
    file.seek(0, os.SEEK_END)  # 相对于末尾向前偏移0个字符
    text = file.read(5)
    print(text) # 读不到内容是空字符串
    file.close()

def seek_cur():
    """
    相对于当前位置不动
    :return:
    """
    file = open('file1', mode='r+', encoding='utf8')
    file.seek(0, os.SEEK_CUR) # 相对于当前位置偏移
    text = file.read(5)
    print(text)
    file.close()

def seek_b_cur():
    """
    在b模式下，读取到的是字节流，读取文件、音频、视频
    :return:
    """
    file = open('file1', mode='rb+')
    file.seek(5, os.SEEK_CUR)
    file.seek(-2, os.SEEK_CUR)
    file.seek(-3, os.SEEK_END)
    b = file.read()  # 得到的是字节流
    print(b)
    file.close()

def copy_b():
    file1 = open('img.png', mode='rb+')
    file2 = open('baidu.png', mode='wb')
    b = file1.read()
    file2.write(b)
    file1.close()
    file2.close()

def modify_movie():
    file1 = open('img.png', mode='rb+')
    file1.seek(10, os.SEEK_SET)
    b = file1.read(1)
    inverted_b = bytes([~b[0] & 0xFF])
    # print(f"取反后的字节: {inverted_b}")
    # print(b)
    # 定位回原来位置
    file1.seek(10, os.SEEK_SET)

    # 写回取反后的字节
    file1.write(inverted_b)
    print("已写回取反后的字节")
    file1.close()



if __name__ == '__main__':
    seek_start()
    # seek_end()
    # seek_cur()
    # seek_b_cur()
    # copy_b()
    # modify_movie()